package com.spatio.serving.basic.service.template.core.component.invoker;

import com.spatio.serving.basic.service.template.common.invoke.UserInfoSession;
import com.spatio.serving.basic.service.template.common.invoke.req.SessionGetNewReq;
import com.spatio.serving.common.lib.common.entity.ApiResponse;
import com.spatio.serving.common.lib.common.http.SpatioHttpClient;
import com.spatio.serving.common.lib.common.util.JsonUtil;
import com.spatio.serving.common.lib.common.util.LatencyWatch;
import com.spatio.serving.spring.boot.starter.prometheus.op.impl.HttpInvokePrometheusOp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author GuoPengfei
 * @Date 2024/6/18 14:03
 */
@Component
@Slf4j
public class SessionInvoker {


    @Resource
    private SpatioHttpClient spatioHttpClient;

    @Value("${url.session.get.new}")
    private String urlSessionGerNew;

    public UserInfoSession getUserInfoBySessionId(String sessionId, String uqId) {
        LatencyWatch watch = LatencyWatch.start();
        SessionGetNewReq request = new SessionGetNewReq();
        request.setSessionId(sessionId);
        //request.setUqId(uqId);
        try {
            String responseStr = spatioHttpClient.postWithBody(urlSessionGerNew, JsonUtil.toJson(request), null, 2000);
            HttpInvokePrometheusOp.op().latency("sessionInvoker_getSessionNew", watch.cost(), TimeUnit.MILLISECONDS);
            HttpInvokePrometheusOp.op().qpsTotal("sessionInvoker_getSessionNew");
            if (responseStr == null) {
                log.error("sessionInvoker.getSessionNew: HTTP result body is null");
                return null;
            }
            ApiResponse apiResponse = JsonUtil.fromJson(responseStr, ApiResponse.class);
            if (apiResponse.getCode() != 0) {
                log.error("sessionInvoker.getSessionNew: code is error, sessionId:{} response={}", sessionId, responseStr);
                return null;
            }
            return JsonUtil.fromJson(JsonUtil.toJson(apiResponse.getResult()), UserInfoSession.class);
        } catch (Exception e) {
            log.error("sessionInvoker.getSessionNew: Exception occurred sessionId:{}", sessionId, e);
            return null;
        }
    }
}